package com.atguigu.yygh.oss.service.impl;/*
 * @author: XueYouPeng
 * @time: 2023/6/14 21:18
 */

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.atguigu.yygh.oss.service.OssService;
import com.atguigu.yygh.oss.util.ConstantProperties;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    @Override
    public String upload(MultipartFile file) {
        //参数提取到配置文件中
        String endpoint = ConstantProperties.ENDPOINT;
        String accessKeyId = ConstantProperties.ACCESSKEYID;
        String accessKeySecret = ConstantProperties.ACCESSKEYSECRET;
        String bucketName = ConstantProperties.BUCKETNAME;

        //日期/文件名称 yyyy/MM/dd

        String dir = new DateTime().toString("yyyy/MM/dd");

        //文件：  uuid + 原文件名(带后缀)
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String filename = file.getOriginalFilename();

        String objectName = dir + "/" + uuid+filename;



        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build("https://" + endpoint, accessKeyId, accessKeySecret);

        try {
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName,file.getInputStream());
            PutObjectResult result = ossClient.putObject(putObjectRequest);
        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        String url = "https://"+bucketName+"."+endpoint+"/" + objectName;
        return url;
    }
}
